<template>
  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入医生名进行查询" style="width: 200px" v-model="data.doctorName"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load()">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div class="table">
        <el-table :data="data.tableData" strip >
          <el-table-column prop="doctorName" label="医生姓名" fixed width="85"></el-table-column>
          <el-table-column prop="id" label="就诊单ID" width="85"></el-table-column>
<!--          <el-table-column prop="patientId" label="患者ID"></el-table-column>-->
          <el-table-column prop="registrationId" label="挂号单ID" width="120"></el-table-column>
          <el-table-column prop="hospitalized" label="是否住院" >
            <template v-slot="scope">
              <el-tag
                  :type="getStatusTagType(scope.row.hospitalized)"
                  disable-transitions
              >
                {{ scope.row.hospitalized }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="hospitalizationId" label="住院单ID" width="120"></el-table-column>
          <el-table-column prop="prescribedMedicine" label="是否开药" >
            <template v-slot="scope">
              <el-tag
                  :type="getStatusTagType(scope.row.prescribedMedicine)"
                  disable-transitions
              >
                {{ scope.row.prescribedMedicine }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prescriptionId" label="药单ID" width="120"></el-table-column>
          <el-table-column prop="diagnosis" label="诊断信息" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column prop="treatmentPlan" label="治疗方案" width="180"  show-overflow-tooltip></el-table-column>
          <el-table-column prop="medicalAdvice" label="医嘱" width="180"  show-overflow-tooltip></el-table-column>
          <el-table-column prop="createdTime" label="叫号时间" width="180"></el-table-column>
          <el-table-column prop="endTime" label="结束就诊时间" width="180"></el-table-column>
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template v-slot="scope">
              <el-button type="primary" @click="lookHadAddOuter(scope.row.prescriptionId)" style="margin-top: 5px" v-if="scope.row.prescribedMedicine === '是'">查看我的药单</el-button>
              <!-- 显示“查看住院信息”按钮 -->
              <el-button
                  v-if="scope.row.hospitalizationId"
                  type="success"
                  @click="lookHospitalizationInfo(scope.row.hospitalizationId, scope.row.patientId)"
                  style="margin-top: 5px; margin-left: 5px"
              >
                查看住院信息
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              style="margin-top: 5px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="data.pageNum"
              :page-sizes="[3, 5, 10, 15, 20]"
              :page-size="data.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total">
          </el-pagination>
        </div>
      </div>
      <el-dialog title="以下是您的药单详情" v-model="data.hadAddVisited" width="70%" :close-on-click-modal="false" destroy-on-close>
        <div class="card">
          <div style="font-size: 20px">本药单总金额为：<span style="color: crimson; font-size: 35px">{{ data.prescriptionInfo.totalCost }}</span> 元</div>
        </div>
        <div class="card">
          <el-table :data="data.itemData" strip >
            <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>
            <el-table-column prop="prescriptionId" label="药单ID"></el-table-column>
            <el-table-column prop="drugId" label="药品ID"></el-table-column>
            <el-table-column prop="drugName" label="药品名"></el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
            <el-table-column prop="unitPrice" label="单价"></el-table-column>
            <el-table-column prop="totalPrice" label="总价"></el-table-column>
            <el-table-column prop="usageInstructions" label="使用说明"></el-table-column>
          </el-table>
        </div>
        <div class="card">
          <div style="font-size: 25px;color: black">药单备注：</div>
          <div style="font-size: 18px;margin-top: 5px">{{data.prescriptionInfo.notes}}</div>
        </div>
      </el-dialog>

      <el-dialog title="住院信息" width="40%" v-model="data.hospitalizationInfoVisible" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="data.hospitalizationInfo" label-width="100px" style="padding-right: 50px">
          <!--          <el-form-item label="患者id" prop="patientId">-->
          <!--            <el-input v-model="data.hospitalizationInfo.patientId" autocomplete="off" />-->
          <!--          </el-form-item>-->
          <el-form-item label="入院日期" prop="admissionDate">
            <el-date-picker
                v-model="data.hospitalizationInfo.admissionDate"
                type="date"
                placeholder="选择入院日期"
                style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="出院日期" prop="dischargeDate">
            <el-date-picker
                v-model="data.hospitalizationInfo.dischargeDate"
                type="date"
                placeholder="选择出院日期"
                style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="科室id" prop="departmentId">
            <el-input v-model="data.hospitalizationInfo.departmentId" autocomplete="off" />
          </el-form-item>
          <el-form-item label="床位号" prop="bedNumber">
            <el-input v-model="data.hospitalizationInfo.bedNumber" autocomplete="off" />
          </el-form-item>
          <el-form-item label="住院原因" prop="admissionReason">
            <el-input v-model="data.hospitalizationInfo.admissionReason" autocomplete="off" />
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'

// 定义响应式数据
const data = reactive({
  tableData: [],  // 表格数据
  pageNum: 1,     // 当前页码
  pageSize: 10,   // 每页显示数量
  total: 0,       // 总记录数
  name: null,     // 搜索条件
  formVisible: false, // 表单显示状态
  form: {},       // 表单数据
  hospitalizationInfoVisible: false,
  hospitalizationInfo: {},
  ids: [],        // 选中数据的ID
  doctorName: null,
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  hadAddVisited: false,
  itemData: [],
  prescriptionInfo: {}
})

// 分页查询
const load = () => {

  request.get('/PatientVisit/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      doctorName: data.doctorName,
      patientId: data.user.id
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 重置筛选条件
const reset = () => {
  data.doctorName = null
  load()
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load(pageNum)
}
const handleSizeChange=(pageSize)=> {
  data.pageSize = pageSize
  load()
}

// 页面初始化加载数据
load()

const lookHadAddOuter = (prescriptionId) =>{
  data.hadAddVisited = true
  loadItemOuter(prescriptionId)
  loadPrescriptionInfo(prescriptionId)
}
const loadItemOuter = (prescriptionId) => {
  request.get('/prescriptionItem/selectPage', {
    params: {
      pageNum: 1,
      pageSize: 10000,
      prescriptionId: prescriptionId
    }
  }).then(res => {
    if (res.code === '200') {
      data.itemData = res.data?.list
      console.log(data.itemData)
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const loadPrescriptionInfo = (prescriptionId) => {
  request.get('/prescription/selectById/'+ prescriptionId).then(res => {
    if (res.code === '200') {
      data.prescriptionInfo = res.data
    } else {
      ElMessage.error(res.msg)
    }
})
}


const lookHospitalizationInfo = (hospitalizationId, patientId) => {
  // 将 hospitalizationId 转换为整数
  const id = parseInt(hospitalizationId, 10);
  // 打开住院信息对话框
  data.hospitalizationInfoVisible = true;
  // 调用 API 获取住院信息数据，传递患者 ID
  loadHospitalizationInfo(id, patientId);
}


const loadHospitalizationInfo = (id, patientId) => {
  request.get('/Admissions/selectById/'+ id, {
    // params: {
    //   id: hospitalizationId,
    //   patientId: patientId
    // }
  }).then(res => {
    if (res.code === '200') {
      // 假设住院信息数据存储在 data.hospitalizationInfo 中
      data.hospitalizationInfo = res.data;
      data.id=id;
      data.patientId=patientId;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(() => {
    ElMessage.error('获取住院信息失败');
  });
}

// 根据挂号状态返回对应的标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '是':
      return 'success';
    case '否':
      return 'danger';
    default:
      return 'primary';
  }
};
</script>

